// components/fumtime-comp/funtime-comp.js
let app = getApp()
const db = wx.cloud.database({env: app.globalData.CLOUD_ENV})
const DBFunny = db.collection('db_funny')
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    title: '',
    text: '',
    content: '',
    isShow: false
  },
  lifetimes: {
    created(){
      this.getFunny();
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    async addMessageFunc(data={}){
      let  {title,text} = data;
      let openid = wx.getStorageSync('openid')
      if(openid){
        if(title != undefined &&text != undefined) {
          let res = await DBFunny.where({title}).get()
          // console.log('yyy:', res);
          if(res.data.length == 0){
            return DBFunny.add({data:{openid , result: {text, title}}}).then(
              content=>{
                  // console.log('xxxx:',content)
              }
            )
          }
          
        }
      }
     
    },
      getFunny(){
        let that = this;
         wx.request({
           url: 'https://api.qqij.cn/Api/Xiaohua?format=json',
           method: 'GET',
           success(response){
            //  console.log(response.data)
             let {code, data:{text, title}} = response.data;
             if(code == "200"){
               that.setData({
                text,
                title,
                isShow: true
               })
              //  插入数据库
               that.addMessageFunc({text, title})
             }
            //  else {
            //    that.setData({isShow: false})
            //  }
           }
         })
      }
  }
})
